﻿using Flurl.Http;
using NineApi;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace NineApiTest
{
    internal class Helper
    {
        public static void OpenUrl(string url)
        {
            try
            {
                // 使用Process.Start方法打开默认浏览器并访问指定URL
                Process.Start(new ProcessStartInfo
                {
                    FileName = url,
                    UseShellExecute = true
                });
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"无法打开浏览器：{ex.Message}");
            }
        }

        public static void OpenHtml(string content)
        {
            try
            {
                

                // 将网页内容保存为本地HTML文件
                string htmlFilePath = "temp.html"; // 保存为本地的文件路径，可以根据需要修改
                File.WriteAllText(htmlFilePath, content);

                // 使用Process.Start方法打开默认浏览器并显示本地HTML文件
                Process.Start(new ProcessStartInfo
                {
                    FileName = htmlFilePath,
                    UseShellExecute = true
                });
            }
            catch (FlurlHttpException ex)
            {
                Debug.WriteLine($"请求发生错误：{ex.Message}");
            }
        }

        public static string GetRedirect(string htmlContent)
        {
            // 使用正则表达式从HTML内容中提取window.location.href后面的URL
            // 正则表达式的模式根据具体HTML内容进行调整
            Match match = Regex.Match(htmlContent, "window.location.href='([^']+)'");

            if (match.Success && match.Groups.Count > 1)
            {
                 var url=Api._url+ match.Groups[1].Value;
                  OpenUrl(url);
            }

            return GetTradeNo(htmlContent);

        }

        private static string GetTradeNo(string htmlContent)
        {
            string tradeNoValue = "";
            string tradeNoPattern = @"trade_no=(\d+)";
            Match match = Regex.Match(htmlContent, tradeNoPattern);

            if (match.Success && match.Groups.Count > 1)
            {
                  tradeNoValue = match.Groups[1].Value;
                Debug.WriteLine($"匹配到的 trade_no 值：{tradeNoValue}");
            }
            else
            {
                Debug.WriteLine("未找到匹配的 trade_no 值。");
            }
            return tradeNoValue;
        }

     
    }
}
